package cn.jy.ad.service;

import cn.jy.ad.mapper.AiDialogueMapper;
import cn.jy.common.ad.domain.AiDialogue;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.zhipu.oapi.ClientV4;
import com.zhipu.oapi.Constants;
import com.zhipu.oapi.service.v4.model.ChatCompletionRequest;
import com.zhipu.oapi.service.v4.model.ChatMessage;
import com.zhipu.oapi.service.v4.model.ChatMessageRole;
import com.zhipu.oapi.service.v4.model.ModelApiResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class ZhipuAIService {

    private static final String requestIdTemplate = "req-%d";

    private ClientV4 client;
    private ObjectMapper mapper;
    @Autowired
    private AiDialogueMapper aiDialogueMapper;

    // 使用 @Value 注入 API 密钥
    public ZhipuAIService(@Value("${api.secret.key}") String apiSecretKey) {
        this.client = new ClientV4.Builder(apiSecretKey).build();
        this.mapper = new ObjectMapper();
    }
    public String decodePrompt(String encodedPrompt) {
        try {
            // 使用 UTF-8 编码进行解码
            return URLDecoder.decode(encodedPrompt, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            log.error("解码失败: {}", e.getMessage());
            return null; // 或者返回一个默认值
        }
    }

    public String generateResponse(String prompt) {
        // 解码用户输入的提示
        String decodedPrompt = decodePrompt(prompt);
        int lastIndex = decodedPrompt.lastIndexOf('=');
        String result;
        if (lastIndex == -1) {
            // 没有找到等号，返回原始字符串
            result = decodedPrompt;
        } else {
            // 获取最后一个等号之前的子字符串，不包含最后一个等号
            result = decodedPrompt.substring(0, lastIndex);
        }
        List<ChatMessage> messages = new ArrayList<>();
        ChatMessage chatMessage = new ChatMessage(ChatMessageRole.USER.value(), prompt);
        messages.add(chatMessage);
        String requestId = String.format(requestIdTemplate, System.currentTimeMillis());
        ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest.builder()
               .model(Constants.ModelChatGLM4)
               .stream(Boolean.FALSE)
               .invokeMethod(Constants.invokeMethod)
               .messages(messages)
               .requestId(requestId)
               .build();

        ModelApiResponse invokeModelApiResp = client.invokeModelApi(chatCompletionRequest);
        // 创建 ObjectMapper 实例
        ObjectMapper mapper = new ObjectMapper();
        try {
            // 将整个响应对象转换为 JSON 节点
            JsonNode rootNode = mapper.readTree(mapper.writeValueAsString(invokeModelApiResp));

            // 导航到 "data" 节点，然后到 "choices" 数组
            JsonNode choicesArray = rootNode.path("data").path("choices");

            // 遍历 "choices" 数组
            for (JsonNode choiceNode : choicesArray) {
                // 对于每个选择，获取 "message" 节点，然后获取 "content" 字段
                String content = choiceNode.path("message").path("content").asText();
                AiDialogue aiDialogue = new AiDialogue();
                aiDialogue.setAiIssue(result);
                aiDialogue.setAiAnswer(content);
                aiDialogueMapper.insert(aiDialogue);
            }
            return mapper.writeValueAsString(invokeModelApiResp);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return null;
        }
    }

    public List<AiDialogue> list() {
        Integer pageSize = aiDialogueMapper.pageSize();
        return aiDialogueMapper.list(pageSize);
    }
}